﻿using System;
using System.Web;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Commonlib;
using Albon.Model;
namespace BLL
{
    public class UserBLL
    {
        private readonly DAL.UserDAL userdal = new DAL.UserDAL();
        private readonly DAL.CookieDAL cookiedal = new DAL.CookieDAL();

        /// <summary>
        /// 根据ID获取相应用户的信息
        /// </summary>
        public DataTable getUserByID(string userid)
        {
            return userdal.getUser("ID=" + userid);
        }
        /// <summary>
        /// 根据用户名获取相应用户的信息
        /// </summary>
        public DataTable getUserByName(string username)
        {
            return userdal.getUser("userName='" + username + "'");
        }

        ///<summary>
        ///新建帐户（只添加用户名，密码，所属角色，信誉与否，最大登录数，默认发货方式 ，默认付款方式,及是否可用 ）
        /// </summary>
        public bool alterUser(UserAccount user)
        {
            return userdal.alterUser(user);
        }

        /// <summary>
        /// 删除用户(同时删除一系列相关信息)
        /// </summary>
        public string delUser(int id)
        {
            if (userdal.delUser(id))
            { 
                //删除其它相关信息
            }
            return "都删除了哪些表的信息";
        }

        /// <summary>
        /// 修改帐户信息（用户名不可修改，密码,是否可用及是否在线通过单独的功能模块来修改）
        /// </summary>
        public bool updateUser(UserAccount user)
        {
            return userdal.userDetails(user);
        }

        /// <summary>
        /// 登录（每次登录之前先登出）
        /// </summary>
        public string Login(string name,string psw)
        {

            Logout();

            if (checkAccount(name, psw))//第一步，验证用户名和密码
            {
                //第二步，验证cookie 并写入登录信息或错误信息
                return checkCookie(name);
            }
            else return "Username or Password is not correct!";
            
        }
        /// <summary>
        /// 登出
        /// </summary>
        public void Logout()
        {
            System.Web.Security.FormsAuthentication.SignOut();
        }
        /// <summary>
        /// 帐户验证
        /// </summary>
        private bool checkAccount(string name,string psw)
        {
            return userdal.checkAccount(name, psw);
        }
        /// <summary>
        ///  cookie验证
        /// </summary>
        private string checkCookie(string name)
        {
           string ret = "";
           string cookievalue= CookieHelper.GetCookieValue(name);
               if (cookievalue!=string.Empty)
               {
                   DataTable dt=cookiedal.getCookie(name).Tables[0];
                   if (dt.Rows.Count == 0)
                   {
                       ret = "No Data";
                   }
                   else
                   {
                       foreach (DataRow dr in dt.Rows)
                       {
                           string computerName = dr["computerName"].ToString();
                           string regname = dr["regName"].ToString();
                           string email = dr["email"].ToString();
                           string browser = dr["browser"].ToString();
                           string createdate = dr["createDate"].ToString();
                           bool passed = bool.Parse(dr["passed"].ToString());
                           string cookieserver = computerName + "$" + regname + "$" + email + "$" + browser + "$" + createdate;
                           if (cookieserver == cookievalue)
                           {
                               if (passed == true)
                               {
                                   //提交验证信息（Forms验证）
                                   System.Web.Security.FormsAuthentication.SetAuthCookie(name, false);
                                   ret = "Success"; break;
                               }
                               else
                               {
                                   ret = "Wait Pass"; break;
                               }
                           }
                           else
                           {
                               ret = "No Match";
                           }
                       }

                   }

               }
               else
               {
                   ret = "No Cookies";
               }
           return ret;
        }



        /// <summary>
        /// 根据用户名获取角色ID
        /// </summary>
        public int getRoleID(string username)
        {
            DataTable dt=getUserByName(username);
            if (dt.Rows.Count > 0)
            {
                return int.Parse(dt.Rows[0]["roleID"].ToString());
            }
            else return 0;
        }
        /// <summary>
        /// 获取该用户默认的付款方式 
        /// </summary>
        public string getPayMethod(string username)
        {
            DataTable dt=getUserByName(username);
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0]["payMethod"].ToString();
            }
            else
            {
                throw new Exception("User Not Exists in UserView!");
            }
        }
        /// <summary>
        /// 获取该用户默认的发货方式 
        /// </summary>
        public string getShipMethod(string username)
        {
            DataTable dt = getUserByName(username);
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0]["shipMethod"].ToString();
            }
            else
            {
                throw new Exception("User Not Exists in UserView!");
            }
        }

        /// <summary>
        /// 根据登录用户名获取当前用户的菜单列表
        /// </summary>
        public string getMenuList(string username)
        {
            DAL.RoleDAL roledal = new DAL.RoleDAL();
            return roledal.getRole("ID=" + getRoleID(username)).Rows[0]["menuList"].ToString();
        }

        /// <summary>
        /// 登录用户是否为Dealer
        /// </summary>
        /// <returns></returns>
        public bool isDealer
        {
            get
            {
                int roleID = getRoleID(HttpContext.Current.User.Identity.Name);
                return roleID == 2;
            } 
        }

        /// <summary>
        /// 登录用户是否为管理员
        /// </summary>
        public bool isAdmin
        {
            get
            {
                int roleID = getRoleID(HttpContext.Current.User.Identity.Name);
                return roleID == 1;
            }
        }

        public bool isAccountant
        {
            get
            {
                int roleID = getRoleID(HttpContext.Current.User.Identity.Name);
                return roleID ==4||roleID==1;
            }
        }
    }
}
